---
import { getCollection } from 'astro:content';
import { config_site } from '../../utils/config-adapter';
import { processFrontmatter } from '../../integrations/process-frontmatter';
import dayjs from 'dayjs';
import TagsLayout from '../../layouts/TagsLayout.astro';

export async function getStaticPaths() {
  // 获取所有文章并处理frontmatter
  const allPosts = await getCollection('posts');
  const processedPosts = await Promise.all(allPosts.map(post => processFrontmatter(post)));
  
  // 提取所有唯一标签及其统计信息
  const tagStats = new Map();
  processedPosts.forEach(post => {
    const tags = post.data.tags || [];
    tags.forEach((tag: String) => {
      if (tag.trim()) {
        const tagName = tag.trim();
        if (!tagStats.has(tagName)) {
          tagStats.set(tagName, {
            count: 0,
            posts: [],
            latestDate: null
          });
        }
        const stats = tagStats.get(tagName);
        stats.count++;
        stats.posts.push(post);
        const postDate = new Date(post.data.date);
        if (!stats.latestDate || postDate > stats.latestDate) {
          stats.latestDate = postDate;
        }
      }
    });
  });
  
  // 为每个标签创建路径参数
  return Array.from(tagStats.entries()).map(([tag, stats]) => ({
    params: { tag },
    props: { 
      tag,
      tagStats: stats
    }
  }));
}

const { tag, tagStats } = Astro.props;

// 获取所有文章并处理frontmatter
const allPosts = await getCollection('posts');
const processedPosts = await Promise.all(allPosts.map(post => processFrontmatter(post)));

// 过滤包含特定标签的文章
const taggedPosts = processedPosts.filter(post => 
  (post.data.tags || []).includes(tag)
);

// 排序文章
const sortedPosts = taggedPosts.sort((a, b) => {
  const dateA = a.data.date ? new Date(a.data.date).getTime() : 0;
  const dateB = b.data.date ? new Date(b.data.date).getTime() : 0;
  return dateB - dateA; // 降序排序
});

// SEO优化的页面元数据
const pageTitle = `标签: ${tag} | ${config_site.siteName}`;
const pageDescription = `探索 ${tag} 相关的 ${sortedPosts.length} 篇文章，包含最新的见解和思考。最后更新于 ${dayjs(tagStats.latestDate).format('YYYY年MM月DD日')}`;
const pageUrl = `${config_site.url}/tags/${encodeURIComponent(tag)}/`;
const pageKeywords = `${tag}, 标签, 文章, 博客, ${config_site.siteName}, ${sortedPosts.slice(0, 5).map(p => p.data.title).join(', ')}`;

// 结构化数据
const structuredData = {
  "@context": "https://schema.org",
  "@type": "CollectionPage",
  "name": pageTitle,
  "description": pageDescription,
  "url": pageUrl,
  "author": {
    "@type": "Person",
    "name": config_site.author
  },
  "publisher": {
    "@type": "Organization",
    "name": config_site.siteName,
    "url": config_site.url
  },
  "mainEntity": {
    "@type": "ItemList",
    "numberOfItems": sortedPosts.length,
    "itemListElement": sortedPosts.slice(0, 10).map((post, index) => ({
      "@type": "ListItem",
      "position": index + 1,
      "item": {
        "@type": "Article",
        "name": post.data.title,
        "url": `${config_site.url}/posts/${post.data.abbrlink}/`,
        "datePublished": post.data.date,
        "author": {
          "@type": "Person",
          "name": config_site.author
        }
      }
    }))
  },
  "breadcrumb": {
    "@type": "BreadcrumbList",
    "itemListElement": [
      {
        "@type": "ListItem",
        "position": 1,
        "name": "首页",
        "item": config_site.url
      },
      {
        "@type": "ListItem",
        "position": 2,
        "name": "标签",
        "item": `${config_site.url}/tags/`
      },
      {
        "@type": "ListItem",
        "position": 3,
        "name": tag,
        "item": pageUrl
      }
    ]
  }
};
---

<TagsLayout
  title={pageTitle}
  description={pageDescription}
  url={pageUrl}
  noindex={false}
  keywords={pageKeywords}
  structuredData={structuredData}
>
  title={pageTitle}
  description={`"${tag}" 标签相关的所有文章`}
  url={config_site.url + '/tags/' + tag}
  noindex={true}
>
  <Fragment slot="header">
    <div data-pagefind-ignore>
    <h1 class="page-title">
      <span class="tag-icon">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"></path>
          <line x1="7" y1="7" x2="7.01" y2="7"></line>
        </svg>
      </span>
      {tag}
    </h1>
    <p class="page-description">共找到 {sortedPosts.length} 篇相关文章</p>
    <a href="/tags/" class="back-link">返回标签云</a>
    </div>
  </Fragment>
  
  <div slot="content" class="post-list-container" data-pagefind-ignore>
    {sortedPosts.length > 0 ? (
      <ul class="post-list">
        {sortedPosts.map(post => (
          <li class="post-item">
            <a href={`/posts/${post.data.abbrlink}/`} class="post-link">
              <div class="post-date">
                {dayjs(post.data.date).format('YYYY-MM-DD')}
              </div>
              <h2 class="post-title">{post.data.title}</h2>
              <br />
              {post.data.description && (
              <p class="post-description">{post.data.description.slice(0,50)+ '...'}</p>
              )}
            </a>
            {post.data.tags && post.data.tags.length > 0 && (
              <div class="post-tags">
                {post.data.tags.map((postTag: unknown) => (
                  <a href={`/tags/${postTag}/`} class={`post-tag ${postTag === tag ? 'current' : ''}`}>
                    {postTag}
                  </a>
                ))}
              </div>
            )}
          </li>
        ))}
      </ul>
    ) : (
      <div class="no-posts">未找到与标签 "{tag}" 相关的文章</div>
    )}
  </div>
</TagsLayout>
